package com.woniuxy.house.service.serviceimpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniuxy.house.entity.*;
import com.woniuxy.house.exception.AccountExistException;
import com.woniuxy.house.exception.AccountNotExistException;
import com.woniuxy.house.exception.NotValidException;
import com.woniuxy.house.exception.PasswordMistakeException;
import com.woniuxy.house.mapper.*;
import com.woniuxy.house.service.UserService;
import com.woniuxy.house.vo.AddSourceVo;
import com.woniuxy.house.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户业务实现类
 *
 * @author baobo
 * @date 2022-08-29-9:52
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private BookingMapper bookingMapper;
	@Autowired
	private PostMapper postMapper;
	@Autowired
	private SourceMapper sourceMapper;
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private HouseDetailMapper houseDetailMapper;
	@Autowired
	private HousePicturesMapper housePicturesMapper;
	@Autowired
	private PasswordEncoder bCryptPasswordEncoder;
	@Autowired
	private PostDetailMapper postDetailMapper;

	@Override
	public User regist(User user) {
		//1.根据用户账号判断是否存在
		if (userMapper.getByAccount(user.getAccount()) != null) {
			//抛出账号已存在异常
			throw new AccountExistException("账号已存在");
		}
		//设置注册时间
		user.setRegistTime(LocalDateTime.now().toString());
		//设置状态
		user.setStatus("1");
		//密码加密
		String password = bCryptPasswordEncoder.encode(user.getPassword());

		//String password = "111";
		user.setPassword(password);
		userMapper.add(user);
		return user;
	}

	public User getUsrById(Integer id) {
		return userMapper.getById(id);
	}


	public List<Source> getUserSources(Integer id) {
		return sourceMapper.getByUserId(id);
	}

	@Transactional
	public User update(User user) {
		userMapper.update(user);
		User newUser = userMapper.getById(user.getId());
		return newUser;
	}

	public void checkUserWithPhone(String account, String phone) {
		User user = userMapper.getByAccount(account);
		if (user == null) {
			throw new AccountNotExistException("账户不存在");
		}
		if (!phone.equals(user.getTelephone())) {
			throw new NotValidException("电话号码错误");
		}
	}

	@Override
	public User getUser(User user) {
		return userMapper.getUser(user.getAccount(), user.getPassword());
	}


	public User resetPassword(User user) {
		//先查询用户信息
		User oldUser = userMapper.getByAccount(user.getAccount());
		//设置密码加密
		String password = bCryptPasswordEncoder.encode(user.getPassword());
		oldUser.setPassword(password);
		userMapper.update(oldUser);
		oldUser.setPassword(null);
		return oldUser;
	}

	public PageBean<List<Booking>> getUserBookings(Integer userId, Integer page) {
		Page<Booking> p = PageHelper.startPage(page, 6);
		List<Booking> bookingList = bookingMapper.getByUserId(userId);
		PageBean pageBean = new PageBean<>();
		pageBean.setPageSzie(6);//分页大小
		pageBean.setCurrPage(page);    //设置当前页数
		pageBean.setTotalNums((int) p.getTotal());//设置总数量
		pageBean.setTotalPage(p.getPages());
		pageBean.setData(bookingList);//设置当前页数的数据
		pageBean.setCurrpageSzie(pageBean.getData().size());//当前页数据数量
		return pageBean;
	}

	@Override
	public PageBean<List<Source>> getUserSources(Integer userId, Integer page) {
		Page<Source> p = PageHelper.startPage(page, 6);
		List<Source> sourceList = sourceMapper.getByUserId(userId);
		PageBean pageBean = new PageBean<>();
		pageBean.setPageSzie(6);//分页大小
		pageBean.setCurrPage(page);    //设置当前页数
		pageBean.setTotalNums((int) p.getTotal());//设置总数量
		pageBean.setTotalPage(p.getPages());
		pageBean.setData(sourceList);//设置当前页数的数据
		pageBean.setCurrpageSzie(pageBean.getData().size());
		return pageBean;
	}

	public PageBean<List<Post>> getUserPosts(Integer userId, Integer page) {
		Page<Post> p = PageHelper.startPage(page, 6);
		List<Post> postList = postMapper.getByUserId(userId);
		PageBean pageBean = new PageBean<>();
		pageBean.setPageSzie(6);//分页大小
		pageBean.setCurrPage(page);    //设置当前页数
		pageBean.setTotalNums((int) p.getTotal());//设置总数量
		pageBean.setTotalPage(p.getPages());
		pageBean.setData(postList);//设置当前页数的数据
		pageBean.setCurrpageSzie(pageBean.getData().size());//当前页数据数量
		return pageBean;
	}

	@Override
	public Source getSourceById(Integer id) {
		return sourceMapper.getById(id);
	}

	public void deleteUserPost(Integer userId, Integer id) {
		Post post = new Post();
		post.setId(id);
		User user = new User();
		user.setId(userId);
		post.setUser(user);
		post.setIsDelete("y");
		postMapper.updateByCondition(post);

	}

	@Transactional
	public List<Message> getHistory(Integer userId, Integer otherId) {
		//获取历史记录
		messageMapper.getByUserIdAndOtherId(userId, otherId);
		//改变记录状态
		messageMapper.updateMessageStatus(userId, otherId);
		//messageMapper
		return messageMapper.getByUserIdAndOtherId(userId, otherId);
	}

	public List<List<Message>> getMessageList(Integer userId) {
		List<Message> messages = messageMapper.getMsgListByUserId(userId);
		List<Integer> ids = new ArrayList<>();
		List<List<Message>> list = new ArrayList<>();
		//拿到所有id
		for (Message m : messages) {
			ids.add(m.getSender().getId());
			ids.add(m.getReceiver().getId());
		}
		//去重
		ids = ids.stream().distinct().collect(Collectors.toList());
		//去除自己id
		for (int i = 0; i < ids.size(); i++) {
			if (ids.get(i) == userId) {
				ids.remove(i);
				break;
			}
		}
		for (int i : ids) {
			List<Message> group = new ArrayList<>();
			for (Message m : messages) {
				if (m.getSender().getId() == i || m.getReceiver().getId() == i) {
					group.add(m);
				}
			}
			list.add(group);
		}
		return list;
	}

	@Override
	public List<User> getAll() {
		return userMapper.getAll();
	}

	@Override
	public PageBean<User> getByPage(int page) {
		PageBean<User> pageBean = new PageBean<>();
		pageBean.setPageSzie(2);//分页大小
		pageBean.setCurrPage(page);    //设置当前页数
		Page p = PageHelper.startPage(pageBean.getCurrPage(), pageBean.getPageSzie());
		List<User> list = userMapper.getAll();
		pageBean.setTotalNums((int) p.getTotal());//设置总数量
		pageBean.setTotalPage(p.getPages());
		pageBean.setData(list);//设置当前页数的数据
		pageBean.setCurrpageSzie(pageBean.getData().size());//当前页数据数量
		return pageBean;
	}

	@Override
	public PageBean<User> getByCondition(User user, int page) {
		PageBean<User> pageBean=new PageBean<>();
		pageBean.setPageSzie(2);
		pageBean.setCurrPage(page);
		Page p = PageHelper.startPage(pageBean.getCurrPage(), pageBean.getPageSzie());
		List<User> list = userMapper.getUserListByCondition(user);//根据条件
		pageBean.setTotalNums((int) p.getTotal());//设置总数量
		pageBean.setTotalPage(p.getPages());
		pageBean.setData(list);//设置当前页数的数据
		pageBean.setCurrpageSzie(pageBean.getData().size());//当前页数据数量
		return pageBean;
	}

	@Override
	public void updateSourceOne(AddSourceVo addSourceVo, Integer id) {
		HouseDetail houseDetail = addSourceVo.getHouseDetail();
		Source source = addSourceVo.getSource();
		String[] housePictures = addSourceVo.getHousePictures();
		houseDetailMapper.update(houseDetail);
		sourceMapper.update(source);
		//查出房源相关图片
		List<HousePictures> oldeHousePictures = housePicturesMapper.selectBySourceId(source.getId());
		//比较图片差异新
		if (housePictures != null) {
			for (int i = 0; i < oldeHousePictures.size(); i++) {
				boolean exist = false;
				for (int j = 0; j < housePictures.length; j++) {
					//如果老图片存在与新图片中则不管，不存在则删除
					if (oldeHousePictures.get(i).getPicture().equals(housePictures[j])) {
						exist = true;
					}
				}
				if (!exist) {
					housePicturesMapper.deletePictureById(oldeHousePictures.get(i).getId());
				}
			}
			//如果新图片存在与老图片中则不管，不存在则添加；
			for (int j = 0; j < housePictures.length; j++) {
				boolean exist = false;
				for (int i = 0; i < oldeHousePictures.size(); i++) {
					if (oldeHousePictures.get(i).getPicture().equals(housePictures[j])) {
						exist = true;
					}
				}
				if (!exist) {
					HousePictures h = new HousePictures();
					h.setSource(source);
					h.setName("");
					h.setPicture(housePictures[j]);
					housePicturesMapper.add(h);
				}
			}
		}
	}

	public void deleteSourceOne(Integer uid, Integer id) {
		sourceMapper.deleteByUserIdAndSourceId(uid, id);
	}

	public Post getPostOne(Integer uid, Integer pid) {
		return postMapper.getByUidAndPid(uid, pid);
	}

	public void updatePostQiu(Integer uid,Post post){
		User user=new User();
		user.setId(uid);
		post.setUser(user);
		postMapper.updateByCondition(post);
		postDetailMapper.update(post.getPostDetail());
	}

	public void deleteUserBooking(Integer uid, Integer id) {
		bookingMapper.deleteBooking(id);
	}

	@Transactional
	public void updateUserPassword(Integer uid, UserVo userVo) {
		//查出用户密码；
		User byId = userMapper.getById(uid);

		boolean matches = bCryptPasswordEncoder.matches(userVo.getOldPassword(), byId.getPassword());
		if (!matches) {
			//密码不对
			throw new PasswordMistakeException("密码不正确");
		}
		User user = new User();
		user.setId(uid);
		user.setPassword(bCryptPasswordEncoder.encode(userVo.getNewPassword()));
		userMapper.update(user);
	}
}